package com.mocaris.android.gank.data

import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.mocaris.android.gank.http.HttpUtil
import com.mocaris.android.gank.http.acceptWanAndroidResponse
import com.mocaris.android.gank.model.Article
import com.mocaris.android.gank.model.Banner
import com.mocaris.android.gank.model.SystemTree
import io.reactivex.Observable

class WanAndroidRepository {

    /**
     * wanAndroid 首页banner
    desc	"一起来做个App吧"
    id	10
    imagePath	"https://www.wanandroid.com/blogimgs/50c115c2-cf6c-4802-aa7b-a4334de444cd.png"
    isVisible	1
    order	2
    title	"一起来做个App吧"
    type	0
    url	"http://www.wanandroid.com/blog/show/2"
     */
    fun getBanner(): Observable<LiveDataResouce<List<Banner>>> {
        return HttpUtil.requestWanAndroid()
            .homeBanner()
            .acceptWanAndroidResponse()
            .flatMap {
                val bannerList = Gson().fromJson<List<Banner>>(it, object : TypeToken<List<Banner>>() {}.type)
                Observable.just(LiveDataResouce(bannerList))
            }
    }

    /**
     * 首页文章
     */
    fun getHomeArticle(page: Int): Observable<LiveDataResouce<Pair<List<Article>, Int>>> {
        return HttpUtil.requestWanAndroid()
            .homeArticlies(page)
            .acceptWanAndroidResponse()
            .flatMap {
                val jsonObject = it.asJsonObject
                val pageCount = jsonObject.get("pageCount").asInt
                val asJsonArray = jsonObject.getAsJsonArray("datas")
                val articleList =
                    Gson().fromJson<List<Article>>(asJsonArray, object : TypeToken<List<Article>>() {}.type)
                Observable.just(LiveDataResouce(Pair<List<Article>, Int>(articleList, pageCount)))
            }
    }

    /**
     * 知识体系
     */
    fun getSysTree(): Observable<List<SystemTree>> {
        return HttpUtil.requestWanAndroid().systemTree()
            .acceptWanAndroidResponse()
            .flatMap {
                val list =
                    Gson().fromJson<List<SystemTree>>(it.asJsonArray, object : TypeToken<List<SystemTree>>() {}.type)
                Observable.just(list)
            }
    }

}